use crate::models::order_returns::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/order-returns", post(create))
        .route("/order-returns/:id", get(get_by_id))
        .route("/order-returns/:id/delete", post(delete))
        .route("/order-returns/by-order/:order_id", get(get_by_order))
        .route(
            "/order-returns/by-order-item/:order_item_id",
            get(get_by_order_item),
        )
        .route("/order-returns/by-status/:status", get(get_by_status))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let order_return = order_returns::Model::create(&state.db, &params).await?;
    format::json(order_return)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let order_return = order_returns::Model::find_by_id(&state.db, &id).await?;
    format::json(order_return)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let order_return = order_returns::Model::find_by_id(&state.db, &id).await?;
    order_return.delete(&state.db).await?;
    format::json(())
}

async fn get_by_order(
    State(state): State<AppContext>,
    axum::extract::Path(order_id): axum::extract::Path<String>,
) -> Result<Response> {
    let order_returns = order_returns::Model::find_by_order_id(&state.db, &order_id).await?;
    format::json(order_returns)
}

async fn get_by_order_item(
    State(state): State<AppContext>,
    axum::extract::Path(order_item_id): axum::extract::Path<String>,
) -> Result<Response> {
    let order_returns =
        order_returns::Model::find_by_order_item_id(&state.db, &order_item_id).await?;
    format::json(order_returns)
}

async fn get_by_status(
    State(state): State<AppContext>,
    axum::extract::Path(status): axum::extract::Path<String>,
) -> Result<Response> {
    let order_returns = order_returns::Model::find_by_status(&state.db, &status).await?;
    format::json(order_returns)
}
